package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.igas.bomp.facade.BompAlipayMchntManageService;
import cc.rengu.igas.bomp.facade.BompMchntManageService;
import cc.rengu.igas.bomp.facade.BompMchntQueryService;
import cc.rengu.igas.bomp.facade.bean.ImageInfoBean;
import cc.rengu.igas.bomp.facade.bean.MchntImageInfoBean;
import cc.rengu.igas.bomp.facade.bean.MchntInfoBean;
import cc.rengu.igas.bomp.facade.request.*;
import cc.rengu.igas.bomp.facade.response.*;
import cc.rengu.igas.bomp.facade.result.Result;
import cc.rengu.redp.bizimpl.enums.AlpaySpecialImageEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.BompTxnNumEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpBMchntImageInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpOrganization;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.ImageInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class AlpaySpecialFeeService {
    private final static Logger logger = LoggerFactory.getLogger(AlpaySpecialFeeService.class);

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntQueryService bompQueryService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompAlipayMchntManageService alipayMchntManageService;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntManageService bompMchntManageService;

    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpBMchntImageInfoService bMchntImageInfoService;

    @Autowired
    private IBizTmpService bizTmpService;

    @Autowired
    private IBizHisService bizHisService;

    @Autowired
    private IUpmpOrganizationService organizationService;

    public IPage<MchntInfoBean> findByPage(HttpServletRequest request,QueryRequest pageable) throws RedpException {
        AlipayActivityApplyQueryResponse res = alipayActivityApplyQuery(request, pageable);
        Page<MchntInfoBean> page = new Page<>();
        SortUtil.handlePageSort(pageable, page, true);
        List<MchntInfoBean> list = Lists.newArrayList();
        if(Common.isBlank(res)){
            page.setRecords(list);
            page.setTotal(0);
        }else {
            list = res.getMchntInfoList();
            page.setRecords(list);
            page.setTotal(res.getTotalRows());
        }
        return page;
    }

    public boolean validate(HttpServletRequest request, Map<String, Object> result) throws RedpException {
        AlipayActivityApplyViewResponse res = alipayActivityApplyView(request);
        if (null == res) {
            throw new RedpException("调用支付宝特殊费率申请查看接口失败");
        }
        //验证 特殊费率申请标志
        // 4-已确认 3-审核拒绝 2-审核通过待确认 1-已申请待审核 0-未申请
        if (res.getSpecialRateApplyFlag().equals("0") ||
                res.getSpecialRateApplyFlag().equals("3")) {
            return true;
        }
        //验证 特殊费率申请结果
        // 0-通过 1-拒绝 2-处理中 3-未申请
        if (null == res.getActivityApplyResult() ||
                res.getActivityApplyResult().equals("3") ||
                res.getActivityApplyResult().equals("1")) {
            return true;
        }

        return false;
    }

    public void uploadImg(HttpServletRequest request, Map<String, Object> result) {
        //TODO 商户影像信息管理	MchntImageInfoManageService 暂未发现有地方调用，后续测试
    }

    /**
     * 支付宝特殊费率申请
     *
     * @param request
     * @return
     */
    public OperationResult applySave(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        //String mchntNo = request.getParameter("mchntNo");
        String imgs = request.getParameter("imgs").replaceAll("&quot;", "\"");
        List<ImageInfoVO> list = JSON.parseArray(imgs, ImageInfoVO.class);//页面显示的图片

        /**
         * 图片处理流程
         */
        //上传图片与商户图片比对 确实是否修改商户影像信息
  //      validateUpdate(request, mchntImageInfoQueryResponse, list);

        //3.根据商户MCC码 选取上送图片。通过alipayImageId 判断是否需要调用图片上传下载接口 同步支付宝
     //   List<MchntImageInfoBean> imgList = getAlpayImages(mchntImageInfoQueryResponse, entity.getIndustryType());

        //支付宝特殊费率申请	AlipayActivityApplyService
        AlipayActivityApplyResponse res = alipayActivityApply(request, list);
        if (!BusinessContainer.BSPS_SUCCESS.equals(res.getRespCode())) {
            log.error("支付宝特殊费率申请处理时失败:code=[{}],msg=[{}]", res.getRespCode(), res.getRespDesc());
            //throw new RedpException("支付宝特殊费率申请处理时失败:"+res.getRespDesc());
            return OperationResult.buildFailureResult("申请失败,"+res.getRespDesc(), result);
        }
        return OperationResult.buildSuccessResult("申请成功", result);
    }

    private void validateUpdate(HttpServletRequest request, MchntImageInfoQueryResponse mchntImageInfoQueryResponse, List<ImageInfoVO> list) {
        //是否需要更新 商户影像信息
        boolean flag = false;
        List<MchntImageInfoBean> mchntImageInfoList = mchntImageInfoQueryResponse.getMchntImageInfoList();
        for (ImageInfoVO img : list) {
            String imageType = AlpaySpecialImageEnum.getImageTypeByName(img.getName());
            if (null == img.getId() || img.getId().equals("")) {
                flag = true;
                //新增的图片
                if (null == mchntImageInfoList) {
                    mchntImageInfoList = new ArrayList<>();
                }

                MchntImageInfoBean bean = null;
                for (MchntImageInfoBean m : mchntImageInfoList) {
                    if (m.getImageType().equals(imageType)) {
                        bean = new MchntImageInfoBean();
                        BeanUtils.copyProperties(m, bean);
                        mchntImageInfoList.remove(m);
                        break;
                    }
                }
                if (null == bean) {
                    bean = new MchntImageInfoBean();
                    bean.setImageType(imageType);
                }

                ImageInfoBean imgBean = new ImageInfoBean();
                imgBean.setImagePath(img.getImagePath());
                imgBean.setImageIndex(img.getImageIndex());

                List<ImageInfoBean> imgBeans = bean.getImageInfoList();
                if (null == imgBeans) {
                    imgBeans = new ArrayList<>();
                    imgBeans.add(imgBean);
                    bean.setImageInfoList(imgBeans);
                } else {
                    imgBeans.add(imgBean);
                    bean.setImageInfoList(imgBeans);
                }
                mchntImageInfoList.add(bean);

            } else {
                for (MchntImageInfoBean m : mchntImageInfoList) {
                    if (m.getImageType().equals(imageType)) {
                        List<ImageInfoBean> imgBeans = m.getImageInfoList();
                        for (ImageInfoBean imgBean : imgBeans) {
                            if (imgBean.getId().equals(img.getId())) {
                                if (!imgBean.getImagePath().equals(img.getImagePath())) {
                                    //图片地址变化 更新
                                    ImageInfoBean imgNew = new ImageInfoBean();
                                    BeanUtils.copyProperties(imgBean, imgNew);
                                    imgNew.setImagePath(img.getImagePath());
                                    imgBeans.remove(imgBean);
                                    imgBeans.add(imgNew);
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }
            if (false) {
                //商户影像接口-更新
        //        mchntImageInfoManage(request, mchntImageInfoList);
            }
        }
    }

    public List<ImageInfoVO> getAllImgType() {
        List<ImageInfoVO> list = new ArrayList<>();
        for (AlpaySpecialImageEnum a : AlpaySpecialImageEnum.values()) {
            list.add(new ImageInfoVO(a.getName(), a.getTitle()));
        }
        return list;
    }

    /**
     * 通过MCC码（行业类别） 获取应上传支付宝的图片
     * 如果图片的支付宝ID为null，调用 图片文件上传下载接口，将图片同步支付宝
     *
     * @param res 商户影像信息
     * @param MCC 行业类型码
     * @return
     */
    private List<MchntImageInfoBean> getAlpayImages(MchntImageInfoQueryResponse res, String MCC) throws RedpException {
        List<MchntImageInfoBean> list = new ArrayList<>();
        String[] imgType = getImgTypeByMCC(MCC);
        if (null != imgType) {
            for (MchntImageInfoBean m : res.getMchntImageInfoList()) {
                for (String type : imgType) {
                    if (m.getImageType().equals(type)) {
                        list.add(m);
                        break;
                    }
                }
            }
        }

        //根据支付宝id 调用 图片上传下载接口
        for (MchntImageInfoBean m : list) {
            for (ImageInfoBean i : m.getImageInfoList()) {
                if (null == i.getAlipayImageId()) {
                    //调用图片接口
                    imageUpDownload(i.getImageId());
                }
            }
        }

        return list;
    }

    public void imageUpDownload(String imgId) throws RedpException {
                // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();

        String traceNo = bMchntBaseInfoService.genMerOrder(user.getInstId());
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.imageFileUpDownload.getType(), user.getInstId(),null));

        req.setUserId(user.getId());
        req.setId(imgId);
        req.setOprType("12");//已有图片文件再上传支付宝
        Result<ImageFileUpDownloadResponse> res;
        String msgName = BompTxnNumEnum.imageFileUpDownload.getDesc();
        try {
            log.info("{}请求报文：{}", msgName, JSON.toJSONString(req));
            res = bompMchntManageService.imageFileUpDownload(req);
            log.info("{}应答报文：{}", msgName, JSON.toJSONString(res));
        } catch (Exception e) {
            log.error(msgName + "处理时系统异常:[{}]", e);
            throw new RedpException(msgName + "处理时系统异常,请联系管理员");
        }
        if (null == res || null == res.getResult()) {
            log.error(msgName + "处理时接口调用失败:result=[{}]", JSON.toJSONString(res));
            throw new RedpException(msgName + "处理时接口调用失败");
        }
        if (!BusinessContainer.BSPS_SUCCESS.equals(res.getResult().getRespCode())) {
            log.error(msgName + "处理时失败:code=[{}],msg=[{}]", res.getResult().getRespCode(), res.getResult().getRespDesc());
            throw new RedpException(msgName + "处理时失败:" + res.getResult().getRespDesc());
        }
    }

    /*
        00-经营执照
        01-法人证件照(人像面)
        02-法人证件照(国微面)
        03-签约协议照
        04-单位证明函照片
        05-资金管理关系证明照
        06-主流餐饮平台入驻证明照
        07-事业单位法人证书照
        08-办学资质照
        09-法人登记证书照
        0A-医疗执业许可证照
        0B-收费样本照
        0C-照会照
        0D-民办非企业单位登记证书
        10-商户门头照
        11-经营场所照
        12-手持证件照
        20-征信报告
        21-征信授权书
        22-联网核查报告
        30-结算账户照(商户结算净额)
        31-结算账户照(商户手续费)
        40-收款设备照
        41-交易凭证照
        42-现场服务工单
        43-商户培训确认表
        44-商户日常检查表
        45-现场培训签字表
        99-其它电子资料
        */
    private String[] getImgTypeByMCC(String MCC) {
        String[] arr4900 = {"00"};
        String[] arr4909 = {"00", "09"};
        String[] arr8651 = {"00", "0B"};
        String[] arr9400 = {"0C", "0B"};
        String[] arr8398 = {"00", "0D", "09"};
        String[] arr8220 = {"07", "08", "00", "01", "02", "10", "40"};//收银台照片(财务处)
        String[] arr8351 = {"07", "08", "0D", "01", "02", "10", "40"};//收银台照片(财务处)
        String[] arr8062 = {"07", "0A", "01", "02", "10", "40"};//收银台照片(挂号处)
        if (MCC.equals("4900") || MCC.equals("4901")
                || MCC.equals("4902") || MCC.equals("4903")) {
            return arr4900;
        } else if (MCC.equals("4909")) {
            return arr4909;
        } else if (MCC.equals("8651") || MCC.equals("9223")
                || MCC.equals("9211") || MCC.equals("9402")
                || MCC.equals("9222") || MCC.equals("9399")
                || MCC.equals("9311") || MCC.equals("9405")) {
            return arr8651;
        } else if (MCC.equals("9400")) {
            return arr9400;
        } else if (MCC.equals("8398")) {
            return arr8398;
        } else if (MCC.equals("8220") || MCC.equals("8211") || MCC.equals("8299")) {
            return arr8220;
        } else if (MCC.equals("8351")) {
            return arr8351;
        } else if (MCC.equals("8062")) {
            return arr8062;
        }
        return null;
    }

    ///////////////////////////////////////////////// 调用接口 /////////////////////////////////////////////////

    /**
     * 商户基本信息查询
     *
     * @param mchntNo
     * @return
     */
    public MchntBaseInfoQueryResponse mchntBaseInfoQuery(String mchntNo) throws RedpException {
                // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        MchntBaseInfoQueryRequest req = new MchntBaseInfoQueryRequest();
        String traceNo = bMchntBaseInfoService.genMerOrder(user.getInstId());
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mchntBaseInfoQuery.getType(), user.getInstId(),"1"));

        req.setUserId(user.getId());
        req.setMchntNo(mchntNo);

        Result<MchntBaseInfoQueryResponse> res;
        String msgName = BompTxnNumEnum.mchntBaseInfoQuery.getDesc();
        try {
            log.info("{}请求报文：{}", msgName, JSON.toJSONString(req));
            res = bompQueryService.mchntBaseInfoQuery(req);
            log.info("{}应答报文：{}", msgName, JSON.toJSONString(res));
        } catch (Exception e) {
            log.error(msgName + "处理时系统异常:[{}]", e);
            throw new RedpException(msgName + "处理时系统异常,请联系管理员");
        }
        if (null == res || null == res.getResult()) {
            log.error(msgName + "处理时接口调用失败:result=[{}]", JSON.toJSONString(res));
            throw new RedpException(msgName + "处理时接口调用失败");
        }
        if (!BusinessContainer.BSPS_SUCCESS.equals(res.getResult().getRespCode())) {
            log.error(msgName + "处理时失败:code=[{}],msg=[{}]", res.getResult().getRespCode(), res.getResult().getRespDesc());
            throw new RedpException(msgName + "处理时失败:" + res.getResult().getRespDesc());
        }
        return res.getResult();
    }

    /**
     * 支付宝特殊费率申请商户列表查询 T00BM015
     *
     * @param request
     * @return
     */
    public AlipayActivityApplyQueryResponse alipayActivityApplyQuery(HttpServletRequest request, QueryRequest pageParam) throws RedpException {
                // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String mchntNo = request.getParameter("mchntNo");
        String instIdASF = request.getParameter("instId");//法人行
        String signInstIdASF = request.getParameter("signInstId");//收单机构
        String mchntNameASF = request.getParameter("mchntName");//商户名称
        String activityTypeASF = request.getParameter("activityType");//活动类型
        String activityApplyResultASF = request.getParameter("activityApplyResult");//活动结果

        if(Common.isBlank(instIdASF)){
            log.error("{}接口调用失败:法人行号不能为空",BompTxnNumEnum.alipayActivityApplyQuery.getDesc());
            return null;
        }

        AlipayActivityApplyQueryRequest req = new AlipayActivityApplyQueryRequest();
        if (StringUtils.isNotBlank(mchntNo)) {
            req.setMchntNo(mchntNo);
        }
        if (StringUtils.isNotBlank(instIdASF)) {
            req.setInstId(instIdASF);
        }
        if (StringUtils.isNotBlank(signInstIdASF)) {
            req.setSignInstId(signInstIdASF);
        }
        if (StringUtils.isNotBlank(mchntNameASF)) {
            req.setMchntName(mchntNameASF);
        }
        if (StringUtils.isNotBlank(activityTypeASF)) {
            req.setActivityType(activityTypeASF);
        }
        if (StringUtils.isNotBlank(activityApplyResultASF)) {
            req.setActivityApplyResult(activityApplyResultASF);
        }

        String traceNo = bMchntBaseInfoService.genMerOrder(user.getInstId());
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.alipayActivityApplyQuery.getType(), instIdASF,null));
        req.setUserId(user.getId());
        req.setPageSize(pageParam.getPageSize());
        req.setPageIndex(pageParam.getPageNum());

        try{
            log.info("法人行["+user.getInstId()+"],用户标识[" + req.getUserId() + "],商户号["+req.getMchntNo()+"]"+BompTxnNumEnum.alipayActivityApplyQuery.getDesc()+"交易请求报文：" + JSON.toJSONString(req));

            Result<AlipayActivityApplyQueryResponse> response= alipayMchntManageService.alipayActivityApplyQuery(req);
            log.info("法人行["+user.getInstId()+"],用户标识[" + req.getUserId() + "],商户号["+req.getMchntNo()+"]"+BompTxnNumEnum.alipayActivityApplyQuery.getDesc()+"交易返回报文：" + JSON.toJSONString(response));
            if(response.isSuccess()){
                AlipayActivityApplyQueryResponse resp = response.getResult();
                // 返回码：00-进件成功，其他均视为失败
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    log.info("法人行["+user.getInstId()+"],用户标识[" + req.getUserId() + "],商户号["+req.getMchntNo()+"]"+BompTxnNumEnum.alipayActivityApplyQuery.getDesc()+"交易成功");
                    return resp;
                }else {
                    log.error("法人行["+user.getInstId()+"],用户标识[" + req.getUserId() + "],商户号["+req.getMchntNo()+"]"+BompTxnNumEnum.alipayActivityApplyQuery.getDesc()+"交易失败");
                    return null;
                }
            }else{
                log.error("法人行["+user.getInstId()+"],用户标识[" + req.getUserId() + "],商户号["+req.getMchntNo()+"]"+BompTxnNumEnum.alipayActivityApplyQuery.getDesc()+"交易没有获得返回信息");
                return null;
            }
        }catch (Exception e) {
            // TODO: handle exception
            log.error("法人行["+user.getInstId()+"],用户标识[" + req.getUserId() + "],商户号["+req.getMchntNo()+"]"+BompTxnNumEnum.alipayActivityApplyQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage(),e);
            throw new RedpException("法人行["+user.getInstId()+"],用户标识[" + req.getUserId() + "],商户号["+req.getMchntNo()+"]"+BompTxnNumEnum.alipayActivityApplyQuery.getDesc()+"交易出现异常，异常信息："+e.getMessage());
        }
    }

    /**
     * 商户影像信息管理 M00BM014
     *
     * @param request
     * @return
     */
    public MchntImageInfoManageResponse mchntImageInfoManage(HttpServletRequest request, List<MchntImageInfoBean> imgList) throws RedpException {
                // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        MchntImageInfoManageRequest req = new MchntImageInfoManageRequest();
        String mchntNo = request.getParameter("mchntNo");
        req.setMchntNo(mchntNo);
        req.setOprType(request.getParameter("oprType"));//操作类型 01-商户影像信息新增 02-商户影像信息修改 03-商户影像信息审核 TODO 根据页面操作判断？
        req.setChecked("0");
        req.setMasterShowFlag("N");

        //处理图片信息
        req.setMchntImageInfoBeanList(imgList);

        String traceNo = bMchntBaseInfoService.genMerOrder(user.getInstId());
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.mchntImageInfoManage.getType(), user.getInstId(),null));

        req.setUserId(user.getId());

        Result<MchntImageInfoManageResponse> res;
        String msgName = BompTxnNumEnum.mchntImageInfoManage.getDesc();
        try {
            log.info("{}请求报文：{}", msgName, JSON.toJSONString(req));
            res = bompMchntManageService.mchntImageInfoManage(req);
            log.info("{}应答报文：{}", msgName, JSON.toJSONString(res));
        } catch (Exception e) {
            log.error(msgName + "处理时系统异常:[{}]", e);
            throw new RedpException(msgName + "处理时系统异常,请联系管理员");
        }
        if (null == res || null == res.getResult()) {
            log.error(msgName + "处理时接口调用失败:result=[{}]", JSON.toJSONString(res));
            throw new RedpException(msgName + "处理时接口调用失败");
        }
        if (!BusinessContainer.BSPS_SUCCESS.equals(res.getResult().getRespCode())) {
            log.error(msgName + "处理时失败:code=[{}],msg=[{}]", res.getResult().getRespCode(), res.getResult().getRespDesc());
            throw new RedpException(msgName + "处理时失败:" + res.getResult().getRespDesc());
        }
        return res.getResult();
    }

    //处理图片信息
    private void buildParam(AlipayActivityApplyRequest req, List<ImageInfoVO> list) {
        for (ImageInfoVO img : list) {
            switch (img.getName()) {
                case "businessLicenseImage":
                    req.setBusinessLicenseImage(img.getAlipayImageId());
                    break;
                case "orgCertImage":
                    req.setOrgCertImage(img.getAlipayImageId());
                    break;
                case "certFaceImage":
                    req.setCertFaceImage(img.getAlipayImageId());
                    break;
                case "certBackImage":
                    req.setCertBackImage(img.getAlipayImageId());
                    break;
                case "settledImage":
                    req.setSettledImage(img.getAlipayImageId());
                    break;
                case "institutionalOrganizationImage ":
                    req.setInstitutionalOrganizationImage(img.getAlipayImageId());
                    break;
                case "runSchoolLicenseImage":
                    req.setRunSchoolLicenseImage(img.getAlipayImageId());
                    break;
                case "artifRegistrationImage":
                    req.setArtifRegistrationImage(img.getAlipayImageId());
                    break;
                case "medicalInstrumentPracticeLicenseImage ":
                    req.setMedicalInstrumentPracticeLicenseImage(img.getAlipayImageId());
                    break;
                case "chargeSampleImage ":
                    req.setChargeSampleImage(img.getAlipayImageId());
                    break;
                case "diplomaticNoteImage":
                    req.setDiplomaticNoteImage(img.getAlipayImageId());
                    break;
                case "privateNonenterpriseUnitsImage  ":
                    req.setPrivateNonenterpriseUnitsImage(img.getAlipayImageId());
                    break;
                case "shopEntranceImage":
                    req.setShopEntranceImage(img.getAlipayImageId());
                    break;
                case "indoorImage":
                    req.setIndoorImage(img.getAlipayImageId());
                    break;
                case "checkstandImage":
                    req.setCheckstandImage(img.getAlipayImageId());
                    break;
                case "certificateFileImage":
                    req.setCertificateFileImage(img.getAlipayImageId());
                    break;
            }
        }
    }

    /**
     * 支付宝特殊费率申请 T00BM016
     *
     * @param request
     * @return
     */
    public AlipayActivityApplyResponse alipayActivityApply(HttpServletRequest request, List<ImageInfoVO> list) throws RedpException {
                // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        AlipayActivityApplyRequest req = new AlipayActivityApplyRequest();
        String mchntNo = request.getParameter("mchntNo");
        req.setMchntNo(mchntNo);
        req.setUserId(user.getId());
        //处理图片信息
        buildParam(req, list);

        String traceNo = bMchntBaseInfoService.genMerOrder(user.getInstId());
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.alipayActivityApply.getType(), user.getInstId(),null));

        Result<AlipayActivityApplyResponse> res;
        String msgName = "支付宝特殊费率申请";
        try {
            log.info("{}请求报文：{}", msgName, JSON.toJSONString(req));
            res = alipayMchntManageService.alipayActivityApply(req);
            log.info("{}应答报文：{}", msgName, JSON.toJSONString(res));
        } catch (Exception e) {
            log.error(msgName + "处理时系统异常:[{}]", e);
            throw new RedpException(msgName + "处理时系统异常,请联系管理员");
        }
        if (null == res || null == res.getResult()) {
            log.error(msgName + "处理时接口调用失败:result=[{}]", JSON.toJSONString(res));
            throw new RedpException(msgName + "处理时接口调用失败");
        }
      /*  if (!BusinessContainer.BSPS_SUCCESS.equals(res.getResult().getRespCode())) {
            log.error(msgName + "处理时失败:code=[{}],msg=[{}]", res.getResult().getRespCode(), res.getResult().getRespDesc());
            throw new RedpException(msgName + "处理时失败:" + res.getResult().getRespDesc());
        }*/
        return res.getResult();
    }

    /**
     * 支付宝特殊费率申请查看	T00BM017
     *
     * @param request
     * @return
     */
    public AlipayActivityApplyViewResponse alipayActivityApplyView(HttpServletRequest request) throws RedpException {
                // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        AlipayActivityApplyViewRequest req = new AlipayActivityApplyViewRequest();
        String mchntNo = request.getParameter("mchntNo");
        req.setMchntNo(mchntNo);
        req.setUserId(user.getId());
        String traceNo = bMchntBaseInfoService.genMerOrder(user.getInstId());
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.alipayActivityApplyView.getType(), user.getInstId(),null));

        Result<AlipayActivityApplyViewResponse> res;
        String msgName = BompTxnNumEnum.alipayActivityApplyView.getDesc();
        try {
            log.info("{}请求报文：{}", msgName, JSON.toJSONString(req));
            res = alipayMchntManageService.alipayActivityApplyView(req);
            log.info("{}应答报文：{}", msgName, JSON.toJSONString(res));
        } catch (Exception e) {
            log.error(msgName + "处理时系统异常:[{}]", e);
            throw new RedpException(msgName + "处理时系统异常,请联系管理员");
        }
        if (null == res || null == res.getResult()) {
            log.error(msgName + "处理时接口调用失败:result=[{}]", JSON.toJSONString(res));
            throw new RedpException(msgName + "处理时接口调用失败");
        }
        if (!BusinessContainer.BSPS_SUCCESS.equals(res.getResult().getRespCode())) {
            log.error(msgName + "处理时失败:code=[{}],msg=[{}]", res.getResult().getRespCode(), res.getResult().getRespDesc());
            throw new RedpException(msgName + "处理时失败:" + res.getResult().getRespDesc());
        }
        return res.getResult();
    }

    /**
     * 将商户影像信息 加载到页面显示的图像bean
     *
     * @param mchntImageInfoQueryResponse
     * @param imageTypes
     */
    public void bulidPageImg(MchntImageInfoQueryResponse mchntImageInfoQueryResponse, List<ImageInfoVO> imageTypes) {
        if (null != mchntImageInfoQueryResponse
                && null != mchntImageInfoQueryResponse.getMchntImageInfoList()) {
            for (MchntImageInfoBean bean :
                    mchntImageInfoQueryResponse.getMchntImageInfoList()) {
                switch (bean.getImageType()) {
                    case "00":
                        buildImageTypeByName(imageTypes, "businessLicenseImage", bean);
                        buildImageTypeByName(imageTypes, "orgCertImage", bean);
                        break;
                    case "01":
                        buildImageTypeByName(imageTypes, "certFaceImage", bean);
                        break;
                    case "02":
                        buildImageTypeByName(imageTypes, "certBackImage", bean);
                        break;
                    case "06":
                        buildImageTypeByName(imageTypes, "settledImage", bean);
                        break;
                    case "07":
                        buildImageTypeByName(imageTypes, "institutionalOrganizationImage ", bean);
                        break;
                    case "08":
                        buildImageTypeByName(imageTypes, "runSchoolLicenseImage", bean);
                        break;
                    case "09":
                        buildImageTypeByName(imageTypes, "artifRegistrationImage", bean);
                        break;
                    case "0A":
                        buildImageTypeByName(imageTypes, "medicalInstrumentPracticeLicenseImage ", bean);
                        break;
                    case "0B":
                        buildImageTypeByName(imageTypes, "chargeSampleImage  ", bean);
                        break;
                    case "0C":
                        buildImageTypeByName(imageTypes, "diplomaticNoteImage", bean);
                        break;
                    case "0D":
                        buildImageTypeByName(imageTypes, "privateNonenterpriseUnitsImage  ", bean);
                        break;
                    case "10":
                        buildImageTypeByName(imageTypes, "shopEntranceImage", bean);
                        break;
                    case "11":
                        buildImageTypeByName(imageTypes, "indoorImage", bean);
                        break;
                    case "40":
                        buildImageTypeByName(imageTypes, "checkstandImage", bean);
                        break;
                }

            }
        }
    }

    /**
     * 将影像信息 加载对应名称的页面影像bean中
     *
     * @param imageTypes
     * @param name
     * @param bean
     */
    private void buildImageTypeByName(List<ImageInfoVO> imageTypes, String name, MchntImageInfoBean bean) {
        for (ImageInfoVO i : imageTypes) {
            if (i.getName().equals(name)) {
                if (null != bean.getImageInfoList() && bean.getImageInfoList().size() > 0) {
                    ImageInfoBean img = bean.getImageInfoList().get(0);
                    BeanUtils.copyProperties(img,i);
                    i.setId(img.getId());
                }
            }
        }
    }

    public OperationResult alipayActivityApplyConfirm(String instId, AlipayActivityApplyConfirmRequest req, BompAlipayMchntManageService alipayMchntManageService, String traceNo) {
        req.setHeader(CommonUtils.packageBompHeader(traceNo, BompTxnNumEnum.alipayActivityApplyConfirm.getType(), instId,null));
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        try {
            log.info(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易请求报文：" + JSON.toJSONString(req));

            Result<AlipayActivityApplyConfirmResponse> response = alipayMchntManageService.alipayActivityApplyConfirm(req);

            log.info(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易返回报文：" + JSON.toJSONString(response));
            if (response.isSuccess()) {
                AlipayActivityApplyConfirmResponse resp = response.getResult();
                // 返回码
                if (BusinessContainer.BSPS_SUCCESS.equals(resp.getRespCode())) {
                    result.put("respCode", resp.getRespCode());
                    result.put("respMsg", resp.getRespDesc());
                    log.error(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易成功");
                    return OperationResult.buildSuccessResult(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易成功", result);
                } else {
                    result.put("respCode", resp.getRespCode());
                    result.put("respMsg", resp.getRespDesc());
                    return OperationResult.buildFailureResult(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易失败", result);
                }
            } else {
                result.put("resCode", BusinessContainer.ERROR);
                result.put("resMsg", BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "没有获得返回报文");
                log.error(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易没有获得返回信息");
                return OperationResult.buildFailureResult(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易失败", result);
            }
        } catch (Exception e) {
            // TODO: handle exception
            result.put("resCode", BusinessContainer.ERROR);
            result.put("resMsg", e.getMessage());
            log.error(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易出现异常，异常信息：" + e.getMessage(), e);
            return OperationResult.buildFailureResult(BompTxnNumEnum.alipayActivityApplyConfirm.getDesc() + "交易失败", result);
        }
    }

    public OperationResult updAlipayImageId(String instId, String mchntNo, String imageType, String imageIndex, String alipayImageId, String imageId){
        try {
            BizTmp bizTmp = bizTmpService.getById(imageId);
            String bizdata = "";
            if (null != bizTmp.getBizData1()) {
                bizdata += bizTmp.getBizData1();
            }
            if (null != bizTmp.getBizData2()) {
                bizdata += bizTmp.getBizData2();
            }
            if (null != bizTmp.getBizData3()) {
                bizdata += bizTmp.getBizData3();
            }
            UpmpBMchntImageInfo bMchntImageInfo = JSON.parseObject(bizdata, UpmpBMchntImageInfo.class);
            bMchntImageInfo.setAlipayImageId(alipayImageId);

                    // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            UpmpOrganization org = organizationService.getOrgByCode(user.getOrgCode(), instId);
            String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            bizTmpService.saveBizTmpDtl(bMchntImageInfo, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    bizTmp.getOprMenuId(), bizTmp.getOprMenuName(), bizTmp.getBizStatus(), bizTmp.getAuditStatus(), imageId, bizTmp.getWebNextUrl(), bizTmp.getDetailFlag(), "", bizTmp.getMchntNo(), bizTmp.getMchntName(), bizTmp.getTermNo());

            bMchntImageInfoService.updAlipayImageId(instId, mchntNo, imageType, Integer.parseInt(imageIndex),alipayImageId);
            Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
            return OperationResult.buildSuccessResult(result);
        } catch (Exception e) {
            log.error(e.getMessage());
            return OperationResult.buildFailureResult("保存影像信息失败");
        }
    }
}
